package com.cy.store.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义一个拦截器
 *
 * @author: AngJie
 * @create: 2022-02-06 18:15
 **/

public class LoginInterceptor implements HandlerInterceptor {

    /**
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  处理器(url+Controller的映射)
     * @return 返回值为true表示放行，false则拦截
     * @author AngJie
     * @creed: Talk is cheap,show me the code
     * @date 2022/2/6 0006 18:21
     */
    // 在调用所有处理请求方法之前被自动调用执行的方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过HttpServletRequest对象来获取session对象
        Object uid = request.getSession().getAttribute("uid");
        // 没有用户信息，重定向到login.html页面
        if (uid == null) {
            response.sendRedirect("/web/login.html");
            return false;
        }
        return true;
    }

    // 在ModelAndView 对象返回之后调用的方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    // 在整个请求所关联的资源别处理完毕后执行的方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
